<!-- 团购页面 -->
<template>
   <div>
      <!-- 头部 -->
      <div>
         <el-input size="" class="input-length" placeholder="请输入商品名称" v-model="list.title" />
         <el-input size="" class="input-length" placeholder="请输入团购ID" v-model="list.id" />
         <el-select placeholder="请选择团购状态" style="width: 200px;margin-right: 10px;" v-model="list.status">
            <el-option label="进行" :value="1" />
            <el-option label="冻结" :value="0" />
         </el-select>
         <el-button type="primary" :icon="Search" @click="init()">查找</el-button>
         <el-button type="primary" :icon="Plus" @click="add">添加</el-button>
      </div>
      <!-- 添加 -->
      <el-drawer v-model="drawer" title="I am the title" :show-close="false" direction="ltr" size="45%"
         style="padding: 0px;">
         <template #header="{ titleId, titleClass }">
            <h4 :id="titleId" :class="titleClass">{{ bool ? '创建团购商品' : '编辑团购商品' }}</h4>
            <el-button @click="drawer = false">取消</el-button>
            <el-button type="primary" @click="addgroup(ruleFormRef)">确定</el-button>
         </template>
         <p style="font-weight: bold;padding: 20px;">商品属性(spu)</p>
         <el-form :model="form" ref="ruleFormRef" :rules="rules">
            <el-form-item label="团购商品" :label-width="formLabelWidth" prop="spuId">
               <el-cascader v-model="form.spuId" :options="options" placeholder="请选择哦"
                  :props="{ children: 'children', label: 'label', value: 'id', emitPath: false }"
                  @change="handleChange"/>
            </el-form-item>
            <el-form-item label="团购时间" :label-width="formLabelWidth" prop="gmtStart">
               <el-date-picker v-model="form.gmtStart" type="datetime" placeholder="选择日期" format="YYYY/MM/DD hh:mm:ss"
                  value-format="x" />至
               <el-date-picker v-model="form.gmtEnd" type="datetime" placeholder="选择日期" format="YYYY/MM/DD hh:mm:ss"
                  value-format="x" />
            </el-form-item>
            <el-form-item label="团购基础人数" :label-width="formLabelWidth" prop="minNum">
               <el-input-number v-model="form.minNum" class="mx-4" :min="1" controls-position="right" />
            </el-form-item>
            <el-form-item label="活动结束时人数没有达到基础人数采取：" :label-width="formLabelWidth">
               <el-radio-group v-model="form.automaticRefund" size="large">
                  <el-radio-button :label="0">不退款，我要发货</el-radio-button>
                  <el-radio-button :label="1">自动退款，我不发货</el-radio-button>
               </el-radio-group>
            </el-form-item>
            <el-card class="box-card">
               <template #header>
                  <div class="card-header">
                     <span style="font-weight: bold;">商品属性(spu)</span>
                     <el-button class="button" type="primary" plain @click="dialog = true">批量定价</el-button>
                     <!-- 批量定价弹出框 -->
                     <el-dialog v-model="dialog" width="30%">
                        <el-form :model="skuGroupShopPrice" ref="ruleFormRef">
                           <el-form-item label="团购价格" :label-width="formLabelWidth">
                              <el-input-number class="mx-4" :min="1" controls-position="right"
                                 v-model.number="skuGroupShopPrice" />
                           </el-form-item>
                        </el-form>
                        <template #footer>
                           <span class="dialog-footer">
                              <el-button @click="dialog = false">取消</el-button>
                              <el-button type="primary" @click="Groupprice"> 确定</el-button>
                           </span>
                        </template>
                     </el-dialog>
                  </div>
               </template>
               <el-table :data="product" style="width: 100%">
                  <el-table-column prop="id" label="skuid" />
                  <el-table-column prop="barCode" label="sku条形码" />
                  <el-table-column prop="specification" label="类型名" />
                  <el-table-column prop="stock" label="库存" />
                  <el-table-column prop="price" label="现价/元" />
                  <el-table-column prop="skuGroupShopPrice" label="团购价格/元" />
                  <el-table-column prop="" label="操作" align="center">
                     <template #default="scope">
                        <el-button size="small" type="primary"
                           @click="handleSwitch(scope.$index, scope.row)">更新</el-button>
                     </template>
                  </el-table-column>
               </el-table>
               <!-- 更新团购价格 -->
               <el-dialog v-model="updateprice" width="30%" title="更新团购价格">
                  <el-form :model="updategroup">
                     <el-form-item label="团购价格" :label-width="formLabelWidth">
                        <el-input-number class="mx-4" :min="1" controls-position="right"
                           v-model="updategroup.skuGroupShopPrice" />
                     </el-form-item>
                     <el-form-item label="现价" :label-width="formLabelWidth">{{ updategroup.price }}元</el-form-item>
                     <el-form-item label="sku类名" :label-width="formLabelWidth">{{ updategroup.specification}}</el-form-item>
                  </el-form>
                  <template #footer>
                     <span class="dialog-footer">
                        <el-button @click="updateprice = false">取消</el-button>
                        <el-button type="primary" @click="handleUpdategroup"> 确定</el-button>
                     </span>
                  </template>
               </el-dialog>
            </el-card>
         </el-form>
      </el-drawer>
      <!-- 表格 -->
      <el-table :data="tableData" border style="width: 100%; margin-top: 20px;">
         <!-- 内层表格 -->
         <el-table-column type="expand">
            <template #default="props">
               <div m="4">
                  <el-descriptions class="margin-top" :column="1" border>
                     <el-descriptions-item label="类目ID">{{ props.row.categoryId }}</el-descriptions-item>
                     <el-descriptions-item label="">
                        <el-table :data="props.row.groupShopSkuDTOList" border>
                           <el-table-column label="skuId" prop="skuId" align="center" />
                           <el-table-column label="规格标题" prop="title" align="center" />
                           <el-table-column label="团购价格" prop="skuGroupShopPrice" align="center" />
                           <el-table-column label="库存" prop="stock" align="center"> 
                              <template #default="scope">{{scope.row.stock}}(件)</template></el-table-column>
                           <el-table-column label="原始价格" prop="originalPrice" align="center" />
                           <el-table-column label="售卖价格" prop="price" align="center" />
                           <el-table-column label="会员价格" prop="vipPrice" align="center" />
                           <el-table-column label="国际条码" prop="barCode" align="center" />
                        </el-table>
                     </el-descriptions-item>
                  </el-descriptions>
               </div>
            </template>
         </el-table-column>
         <!-- 外层表格 -->
         <el-table-column label="团购ID" prop="id" align="center" />
         <el-table-column label="商品ID" prop="spuId" align="center" />
         <el-table-column label="商品名称" prop="title" align="center" />
         <el-table-column label="商品主图" prop="img" align="center">
            <template #default="scope">
               <el-popover effect="light" trigger="hover" placement="right" width="300px">
                  <template #default><el-image :src="scope.row.img" /></template>
                  <template #reference> <el-image :src="scope.row.img" style="width: 50px;height: 50px;" /> </template>
               </el-popover>
            </template>
         </el-table-column>
         <el-table-column label="未满策略" prop="automaticRefund" align="center">
            <template #default="scope"> 
            <el-tag :type="scope.row.automaticRefund ? 'warning' : 'success'">{{scope.row.automaticRefund ? '发货' : '退款'}}</el-tag>
         </template>
         </el-table-column>
         <el-table-column label="活动状态" prop="status" align="center">
            <template #default="scope"> 
               <el-tag>{{ scope.row.status == 1 ? '进行' : '冻结'}}</el-tag>
            </template></el-table-column>
         <el-table-column label="开始时间" prop="gmtStart" align="center">
             <template #default="scope">{{friendTimes(scope.row.gmtStart)}}
            </template></el-table-column>
         <el-table-column label="结束时间" prop="gmtEnd" align="center"> 
            <template #default="scope">{{friendTimes(scope.row.gmtEnd)}}</template></el-table-column>
         <el-table-column label="当前人数" prop="buyerNum" align="center" />
         <el-table-column label="目标人数" prop="minNum" align="center" />
         <el-table-column prop="" label="操作" align="center" width="150">
            <template #default="scope" >
               <div v-if="!scope.row.status">
                  <el-button size="small" type="primary" @click="handleupdate(scope.row)">编辑</el-button>
                  <el-button size="small" type="danger" @click="handledelete(scope.row.id)">删除</el-button>
               </div>
            </template>
         </el-table-column>

      </el-table>
      <Paging v-bind="pagination" @emitfather="CurrentList"></Paging>
   </div>
</template>
<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue'
import { Plus, Search } from '@element-plus/icons-vue'//图标
import { post, get } from '@/utlis/http';
import { friendTimes } from '@/utlis/PackagingTime'
import Paging from '@/components/paging/Pagings.vue'
import { Classproduct, classPagination } from '#/index'
import { ElMessage, type FormInstance } from 'element-plus';
const pagination = reactive(new classPagination())//分页处理
const ruleFormRef = ref<FormInstance>()
const bool = ref(false)
const drawer = ref(false)
const tableData = ref([])
let list = ref<Typegoodsgroup>({
   _gp: 'admin.groupshop',
   _mt: 'list',
   id: "",
   title: '',
   status: "",
   page: 1,
   limit: 10
})
// 渲染列表
function init() {
   get(list.value).then(res => {
      console.log(res);
      let { errmsg, errno, data } = res
      if (200 === errno) {
         tableData.value = data.items//列表
         pagination.total = data.total//总条数
      }

   })
}
// 挂载
onMounted(() => {
   init()
   info()//sku树
})
// 添加表单
let form = ref(new Classproduct())
let product = ref()//获得添加里面sku列表
let formLabelWidth = '140px'
let updateprice = ref(false)//控制更新团购的显示隐藏
let dialog = ref(false)//控制批量定价团购的显示隐藏
let options = ref()//获得团购下拉商品
// 团购商品改变事件
function handleChange(s: number) {
   let detail = {
      _gp: 'admin.product',
      _mt: 'detail',
      spuId: s
   }
   get(detail).then(res => {
      product.value = res.data.skuList
      console.log(product.value);

      // 改变内部原来属性为skuId
      product.value.forEach((item: { skuId: number, id: number }) => {
         item.skuId = item.id
      })
      // 内部添加一个新属性
      product.value.map((v: any) => {
         v.skuGroupShopPrice = undefined
      })


   })

}
// 添加弹窗
function add() {
   bool.value = true
   drawer.value = true
   form.value = new Classproduct()//添加完清空
}
let skuGroupShopPrice = ref(1)
function Groupprice() {//定义的团购价格进行赋值
   for (const s of product.value) {
      if (s.price < skuGroupShopPrice.value) {
         ElMessage.warning('团购不能高于现价')
         return
      } else {
         s.skuGroupShopPrice = skuGroupShopPrice.value
      }
   }
   dialog.value = false
}
// 非空验证
const rules = reactive({
    spuId: [{ message: '团购商品不能为空！', trigger: 'blur' ,required: true}],
    minNum: [{ message: '基础人数不能为空！', required: true, trigger: 'blur' }],
   gmtStart:[{message: '时间不能为空！', required: true, trigger: 'blur'}]
})
// 添加/编辑确认
function addgroup(formEl: FormInstance | undefined) {
   if (!formEl) return
   formEl.validate((valid) => {
      if (valid) {
         let addgroups = {
            _gp: 'admin.groupshop',
            _mt: bool.value ? 'create' : 'edit',
            ...form.value,
            groupShopSkuList: JSON.stringify(product.value)
         }
         post(addgroups).then(res => {
            let { errmsg, errno } = res
            if (200 === errno) {
               drawer.value = false
               ElMessage.success(errmsg + "添加")
               init()
            } else {
               ElMessage.error(errmsg)
            }
         })

      } else {
         return false
      }
   })

}
// 编辑弹出框
function handleupdate(row:any) {
   console.log(row);

   bool.value = false//控制编辑添加
   drawer.value = true//弹窗显示隐藏
   Object.assign(form.value, row)
   row.groupShopSkuDTOList.forEach((s:object) => {
      // 深度拷贝
      product.value = JSON.parse(JSON.stringify(row.groupShopSkuDTOList))
   })
}
// 绑定更新当前行
let updategroup = ref({
   price: '',
   specification: '',
   skuGroupShopPrice: 1

})
// 更新弹窗
let rows = ref()//得到当前行
function handleSwitch(index: number, row: any) {
   rows.value = row
   updateprice.value = true
   updategroup.value.price = row.price
   updategroup.value.specification = row.specification
   updategroup.value.skuGroupShopPrice = row.skuGroupShopPrice

}
// 更新团购价格
function handleUpdategroup() {
   // 当前行价格小于绑定的值提示
   if (rows.value.price < updategroup.value.skuGroupShopPrice) {
      ElMessage.warning('团购价不能高于现价')
   } else {
      rows.value.skuGroupShopPrice = updategroup.value.skuGroupShopPrice
      updateprice.value = false
   }

}

// 删除
function handledelete(id: number) {
   let data = {
      _gp: 'admin.groupshop',
      _mt: 'delete',
      id
   }
   post(data).then(res => {
      let { errmsg, errno } = res
      if (200 === errno) {
         ElMessage.success(errmsg)
         init()
      } else {
         ElMessage.error(errmsg)
      }

   })

}
// 分页
function CurrentList(v: classPagination) {
   list.value.page = v.pageNo
   list.value.limit = v.pageSize
   init()
}
//获取商品spu树
function info() {
   let product = {
      _gp: 'admin.product',
      _mt: 'getSpuBigTree'
   }
   get(product).then(res => {
      // 下拉获得团购商品
      options.value = res.data

   })
}

</script>
<style>
.input-length {
   width: 200px;
   margin-right: 10px;
}

.card-header {
   display: flex;
   justify-content: space-between;
   align-items: center;
}

.el-drawer__body {
   padding: 0px;
}
</style>